﻿using System;
using System.Threading.Tasks;
using Dm;
using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;

namespace Volo.Abp.EntityFrameworkCore.ConnectionStrings
{
    [Dependency(ReplaceServices = true)]
    public class DmConnectionStringChecker : IConnectionStringChecker, ITransientDependency
    {
        public virtual async Task<AbpConnectionStringCheckResult> CheckAsync(string connectionString)
        {
            var result = new AbpConnectionStringCheckResult();
            try
            {
                var connString = new DmConnectionStringBuilder(connectionString);

                var oldDatabaseName = connString.Database;
                connString.Database = "dm";

                await using var conn = new DmConnection(connString.ConnectionString);
                await conn.OpenAsync();
                result.Connected = true;
                await conn.ChangeDatabaseAsync(oldDatabaseName!);
                result.DatabaseExists = true;

                await conn.CloseAsync();

                return result;
            }
            catch (Exception)
            {
                return result;
            }
        }
    }
}
